package com.hfzy.ihk.web.calldata.handlers;

import com.alibaba.fastjson.JSON;
import com.hfzy.ihk.common.constants.GlobalStatic;
import com.hfzy.ihk.common.core.elasticsearch.ElasticsearchLocalCache;
import com.hfzy.ihk.common.core.elasticsearch.ElasticsearchOperation;
import com.hfzy.ihk.common.core.elasticsearch.OperationErrorMsgBiz;
import com.hfzy.ihk.common.core.elasticsearch.base.CommonTableOperationHandler;


import com.hfzy.ihk.common.util.CommonUtils;
import com.hfzy.ihk.common.util.string.StringTools;
import com.hfzy.ihk.common.web.WebResult;
import com.hfzy.ihk.facade.calldata.entity.CallHistory;
import com.hfzy.ihk.facade.calldata.enums.CallDataOperations;
import com.hfzy.ihk.facade.calldata.enums.CallDataTables;
import com.hfzy.ihk.web.calldata.biz.CallHistoryBiz;
import com.hfzy.ihk.web.calldata.biz.CallTaskDetailBiz;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2018/7/19.
 *
 * @author wws
 */
@Component
public class CallHistoryTableOperationHandler extends CommonTableOperationHandler {

    private static final Logger logger = LoggerFactory.getLogger(CallHistoryTableOperationHandler.class);

    @Autowired
    private OperationErrorMsgBiz operationErrorMsgBiz;

    @Autowired
    CallHistoryBiz callHistoryBiz;

    @Autowired
    CallTaskDetailBiz callTaskDetailBiz;

    public CallHistoryTableOperationHandler() {

        /**
         * 必须定义该处理器对应的table和操作名
         * */
        this.table = CallDataTables.CALL_HISTORY;

        this.tableOperation = CallDataOperations.addCallHistory;
    }

    /**
     * 重试错误信息
     * @param elasticsearchOperation
     */
    @Override
    protected void toHandle(ElasticsearchOperation elasticsearchOperation) {
        List data = elasticsearchOperation.getData();

        logger.debug("handle data:{}", JSON.toJSONString(data));

        if(StringTools.isNotempty(data)){
            String jsonStr = data.get(0).toString();
            Map<String,Object> paramMap = JSON.toJavaObject(JSON.parseObject(jsonStr),Map.class);
            CallHistory callHistory = callHistoryBiz.selectById(paramMap.get("sessionId").toString());
            CallHistory oldCallHistory = null;

            if(callHistory != null){//存在就是修改，然后把旧对象存起来
                oldCallHistory = new CallHistory();
                BeanUtils.copyProperties(callHistory,oldCallHistory);
            }else{//不存在就是新增
                callHistory = new CallHistory();
                callHistory.setVersion(1L);
            }
            //把修改的数据set进去
            for(String key : paramMap.keySet()){
                if("version".equals(key)||StringTools.isEmpty(paramMap.get(key))){
                    continue;
                }
                if("targetCallLength".equals(key)){//被叫通话时长
                    Integer targetCallLength = Integer.valueOf(paramMap.get(key).toString());
                    callHistory.setTargetChargingLength((int)Math.ceil((double) targetCallLength/60));
                    continue;
                }
                if("mainCallLength".equals(key)){//主叫通话时长
                    Integer mainCallLength = Integer.valueOf(paramMap.get(key).toString());
                    callHistory.setMainChargingLength((int)Math.ceil((double) mainCallLength/60));
                    continue;
                }
                try {
                    CommonUtils.setObjName(callHistory,key,paramMap.get(key));
                } catch (Exception e) {
                    continue;
                }
            }

            //总计费时长
            Integer totalBillingLength = 0;
            if(StringTools.isNotempty(callHistory.getMainChargingLength())){
                totalBillingLength += callHistory.getMainChargingLength();
            }
            if(StringTools.isNotempty(callHistory.getTargetChargingLength())){
                totalBillingLength += callHistory.getTargetChargingLength();
            }
            callHistory.setTotalBillingLength(totalBillingLength);

            WebResult result = new WebResult();

            Map<String,Object> redisMap = new HashMap<>();

            if(oldCallHistory == null){//新增
                result = callHistoryBiz.saveCallHistory(callHistory);

                if(GlobalStatic.CODE_1.equals(result.getCode())&&paramMap.containsKey("callTaskId")){
                    redisMap = CommonUtils.objectMap(callHistory,null,Arrays.asList(
                            "callTaskId","sessionId","mainCallAnswered","mainCallRinging","targetCallLength",
                            "roundTimes","customerNeedLevel","focusWords"
                    ),false);
                    //用来确保接通次数不会出错
                    if(!redisMap.containsKey("mainCallAnswered")){
                        redisMap.put("mainCallAnswered",true);
                    }
                }
            }else {//修改
                try {
                    Map<String,Object> updateMap =  CommonUtils.compareObj(oldCallHistory,callHistory,
                            Arrays.asList("serialVersionUID","sessionId","version"),null);
                    if(!updateMap.isEmpty()&&paramMap.containsKey("callTaskId")){
                        result = callHistoryBiz.updateCallHistory(updateMap,paramMap.get("sessionId").toString(),oldCallHistory.getVersion());

                        if(GlobalStatic.CODE_1.equals(result.getCode())){
                            redisMap.put("callTaskId",paramMap.get("callTaskId").toString());
                            redisMap.putAll(updateMap);
                            //用来确保接通次数不会出错
                            if(redisMap.containsKey("mainCallAnswered")){
                                redisMap.remove("mainCallAnswered");
                            }
                        }
                    }
                }catch (Exception e){
                    throw new RuntimeException(e);
                }
            }
            if(GlobalStatic.CODE_N.equals(result.getCode())){
                throw new RuntimeException();
            }else if(GlobalStatic.CODE_1.equals(result.getCode())){
                try {//统计存入缓存
                    if(!redisMap.isEmpty()){
                        //callTaskDetailBiz.statisticsCallHistory(redisMap);
                        callTaskDetailBiz.queueStatisticsCallHistory(redisMap);
                    }
                }catch (Exception e){
                    logger.error("补偿通话详情统计放入redis出错，错误信息error:{}",e);
                    ElasticsearchLocalCache.put(redisMap);
                }
            }
        }
    }

    /***
     *
     * 表操作失败的处理
     * */
    public void handleError(ElasticsearchOperation elasticsearchOperation, Exception e) {

        if(elasticsearchOperation.isFromJobRun()){
            return;
        }

        logger.error("处理操作错误：",e);

        operationErrorMsgBiz.dealElasticsearchOperation(elasticsearchOperation,e);
    }
}
